package com.canbot.u05.activity.customvoice;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;

import com.alibaba.fastjson.JSON;
import com.canbot.u05.R;
import com.canbot.u05.activity.BaseActivityNoTitle;
import com.canbot.u05.activity.customvoice.bean.AnswerBean;
import com.canbot.u05.activity.shoppingGuide.sales.TextToSpeechActivity;
import com.canbot.u05.bean.JsonResponse;
import com.canbot.u05.socket.IpMsgConst;
import com.canbot.u05.socket.MsgSendUtils;
import com.canbot.u05.socket.MsgType;
import com.canbot.u05.utils.Logger;
import com.canbot.u05.utils.OkHttpUtils;
import com.canbot.u05.utils.PathConst;
import com.canbot.u05.utils.ToastTools;
import com.canbot.u05.view.RouteRecordDialog;
import com.canbot.u05.view.UsherModeRecordDialog;
import com.canbot.u05.widget.LoadingDialogUtils;

import java.io.File;
import java.util.HashMap;

/**
 * Created by liu.heng  on 2018/5/24.
 * 自定义对话回答方式选择
 */
public class CustomAnswerActivity extends BaseActivityNoTitle implements View.OnClickListener {

        private static final String TAG = CustomAnswerActivity.class.getName();

        private ImageView audio_image;

        private ImageView text_image;

        private ImageView recording_image;

        private final int ADD_ANSWER = 0;

        private final int CHANGE_ANSWER = 1;

        private int type;

        private int answerType = -1;//回答的方式

        private String answer_text = "";

        private String question_Str = "";

        private String oldQuestion;

        private String cmd_id = "";

        private Dialog dialogLoading;

        private AnswerBean mAnswerBean;

        private String fileName;

        private RouteRecordDialog usherModeRecordDialog;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_custom_answer);
                audio_image = (ImageView) findViewById(R.id.audio_image);
                text_image = (ImageView) findViewById(R.id.text_image);
                recording_image = (ImageView) findViewById(R.id.recording_image);

                final Intent intent = getIntent();
                type = intent.getIntExtra("type", -1);
                question_Str = intent.getStringExtra("question_Str");
                oldQuestion = intent.getStringExtra("oldquestion");
                if (type == CHANGE_ANSWER) {
                        resetChooseImage();
                        mAnswerBean = JSON.parseObject(intent.getStringExtra("answer"), AnswerBean.class);
                        cmd_id = mAnswerBean.getCmd_id();
                        answerType = mAnswerBean.getType();
                        if (answerType == 1) {
                                answer_text = mAnswerBean.getTtstext();
                        }
                        else {
                                answer_text = mAnswerBean.getSoundpath();
                        }
                }
        }

        @Override
        protected void onResume() {
                super.onResume();

                resetChooseImage();

                if (answerType == 1) {
                        text_image.setVisibility(View.VISIBLE);
                }
                else if (answerType == 0){
                        audio_image.setVisibility(View.VISIBLE);
                }
                else if (answerType == 2){
                        recording_image.setVisibility(View.VISIBLE);
                }
        }

        private void resetChooseImage() {
                audio_image.setVisibility(View.GONE);
                text_image.setVisibility(View.GONE);
                recording_image.setVisibility(View.GONE);
        }

        /*回答设置选择*/
        public void buttonEvent(View view) {
                resetChooseImage();
                switch (view.getId()) {
                        case R.id.audio_btn://音频
                                audio_image.setVisibility(View.VISIBLE);
                                final Intent intent1 = new Intent(this, ChooseAudioActivity.class);
                                if (type == CHANGE_ANSWER) {
//                                        intent1.putExtra("soundPath", mAnswerBean.getSoundpath());
                                        intent1.putExtra("voice", mAnswerBean.getSoundpath());
                                        intent1.putExtra("path", "/uusound");
                                }else {
                                        intent1.putExtra("path", "/uusound");
                                }
                                startActivityForResult(intent1, 10001);
                                break;
                        case R.id.text_btn://文本转语音
                                text_image.setVisibility(View.VISIBLE);
                                final Intent intent2 = new Intent(this, TextToSpeechActivity.class);
                                if (type == CHANGE_ANSWER) {
                                        intent2.putExtra("voice", mAnswerBean.getTtstext());
                                }
                                startActivityForResult(intent2, 10002);
                                break;
                        case R.id.recording_btn://录音
                                recording_image.setVisibility(View.VISIBLE);
                                record();
                                break;
                        default:
                                break;
                }
        }

        @Override
        public void onClick(View view) {
                switch (view.getId()) {
                        case R.id.record_dialog_finish:
                                fileName = usherModeRecordDialog.ok();
                                Logger.e("test", "fileName" + fileName);
                                usherModeRecordDialog.setTime(CustomAnswerActivity.this.getString(R.string.uploading_please_wait));
                                Logger.d(TAG, "录音的文件名：" + fileName);
                                uploadFile();

                                break;
                        case R.id.record_dialog_cancle:
                                usherModeRecordDialog.no();
                                usherModeRecordDialog.dismiss();
                                Logger.d(TAG, "录音的文件名：" + fileName);
                                break;
                        default:
                                break;
                }
        }

        /**
         * 进入录音
         */
        private void record() {
                resetChooseImage();
                recording_image.setVisibility(View.VISIBLE);
                if (usherModeRecordDialog == null) {
                        //点击语音录入图标
                        usherModeRecordDialog = new RouteRecordDialog(this, RouteRecordDialog.USHER_MODE);
                        usherModeRecordDialog.setFinishClickListener(this);
                        usherModeRecordDialog.setCancleClickListener(this);
                        setDialogWindowAttr(usherModeRecordDialog, this);
                        usherModeRecordDialog.show();
                }
                else {
                        usherModeRecordDialog.show();
                }

        }

        public static void setDialogWindowAttr(Dialog dlg, Context ctx) {
                dlg.setCancelable(false);
                final Window window = dlg.getWindow();
                final WindowManager.LayoutParams lp = window.getAttributes();
                lp.gravity = Gravity.CENTER;
                lp.width = (int) ctx.getResources().getDimension(R.dimen.x536);//宽高可设置具体大小
                lp.height = (int) ctx.getResources().getDimension(R.dimen.x436);
                dlg.getWindow().setAttributes(lp);
        }

        @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
                super.onActivityResult(requestCode, resultCode, data);
                if (requestCode == 10002 && resultCode == Activity.RESULT_OK) {
                        String str = data.getStringExtra("ttsResult");
                        if (!str.isEmpty()) {
                                answer_text = str;
                                answerType = 1;
                        }
                }
                else if (requestCode == 10001 && resultCode == Activity.RESULT_OK) {
                        String str = data.getStringExtra("path");
                        if (!str.isEmpty()) {
                                answer_text = str;
                                answerType = 0;
                        }
                }
                else {
                        return;
                }
        }

        /*确定*/
        public void nextStep(View view) {
                if (type == ADD_ANSWER) {
                        if (!answer_text.isEmpty()) {
                                startActivity(new Intent(this, CustomImageActivity.class)
                                        .putExtra("type", 0)
                                        .putExtra("question_Str", question_Str)
                                        .putExtra("answer_Str", answer_text)
                                        .putExtra("answerType", answerType));
                                MsgSendUtils.sendStringMsg(MsgType.PLAY_SOUND, PathConst.CUSTOM_DIALOG_PAYH + "u05_dztp_001.wav");
                                MsgSendUtils.sendStringMsg(MsgType.EYE_MOTION, "29");
                                MsgSendUtils.sendStringMsg(MsgType.ACTION, "14007");
                                return;
                        }
                        else {
                                ToastTools.newInstance(getApplicationContext()).showText(getString(R.string.answer_cannot_empty));
                        }
                }
                else if (type == CHANGE_ANSWER) {
                        if (!answer_text.isEmpty()) {
                                dialogLoading = LoadingDialogUtils.createLoadingDialog(this, getResources().getString(R.string.request));
                                dialogLoading.show();
                                final HashMap<String, Object> hasMap = new HashMap<>();
                                hasMap.put("type", "2");
                                hasMap.put("newquestion", question_Str);
                                hasMap.put("oldquestion", oldQuestion);
                                hasMap.put("answer", answer_text);
                                hasMap.put("cmd_id", cmd_id);
                                hasMap.put("answertype", String.valueOf(answerType));
                                Log.e(TAG,"----->" + answer_text + "&&" + String.valueOf(answerType));
                                OkHttpUtils.upLoadFile("http://" + IpMsgConst.SOCKET_HOST2 + ":7755/" + "dialogcustom", hasMap, new OkHttpUtils.OkHttpCallBack() {
                                        @Override
                                        public void onSuccess(String result) {
                                                final JsonResponse strMsgBean = JSON.parseObject(result, JsonResponse.class);

                                                final String msg;

                                                if (strMsgBean.getRc() != 0) {
                                                        msg = strMsgBean.getMsg();
                                                }
                                                else {
                                                        msg =CustomAnswerActivity.this.getString(R.string.update_successfully);

                                                }
                                                runOnUiThread(new Runnable() {
                                                        @Override
                                                        public void run() {
                                                                dialogLoading.dismiss();
                                                                ToastTools.newInstance(getApplicationContext()).showText(msg);
                                                                Intent intent = new Intent(CustomAnswerActivity.this, CustomDialogListActivity.class);
                                                                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                                                                startActivity(intent);
                                                                finish();
                                                        }
                                                });
                                        }

                                        @Override
                                        public void onFailure() {
                                                runOnUiThread(new Runnable() {
                                                        @Override
                                                        public void run() {
                                                                dialogLoading.dismiss();
                                                                ToastTools.newInstance(getApplicationContext()).showText(getString(R.string.network_error));
                                                        }
                                                });
                                        }
                                });

                        }
                        else {
                                ToastTools.newInstance(getApplicationContext()).showText(getString(R.string.answer_cannot_empty));
                        }
                }
        }

        //上传到机器人头部的某个文件夹下
        private String url = IpMsgConst.HTTP_URL + "uploadRecord";

        private void uploadFile() {
                HashMap<String, Object> hashMap = new HashMap<>();
                hashMap.put("audiofile", new File(UsherModeRecordDialog.RECORD_FILE_DIR, fileName));
                hashMap.put("path", fileName);
                hashMap.put("dialog","dialog");
                OkHttpUtils.upLoadFile(url, hashMap, new OkHttpUtils.OkHttpCallBack() {
                        @Override
                        public void onSuccess(final String result) {
                                Logger.e(TAG, result + "上传成功");
                                runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                                usherModeRecordDialog.cancel();
                                                ToastTools.newInstance(getApplicationContext()).showText(CustomAnswerActivity.this.getString(R.string.upload_complete));
                                                final String path = fileName;
                                                Logger.e(TAG, "录音文件路径 ：" + path);
                                                answer_text = "/uusound/" + path;
                                                answerType = 0;
                                                Logger.e(TAG,"路径----->"+path);
                                        }
                                });
                        }

                        @Override
                        public void onFailure() {

                                runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                                usherModeRecordDialog.cancel();
                                                ToastTools.newInstance(getApplicationContext()).showText(CustomAnswerActivity.this.getString(R.string.upload_failed));
                                        }
                                });
                        }
                });
        }

        /*返回*/
        public void back(View view) {
                finish();
        }

}
